package com.suixun.queue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.suixun.dao.sendmessagemanage.SendMessageManageDAO;
import com.suixun.entity.SendMessageInfo;
import com.suixun.lib.httpsqs4j.HttpsqsClient;
import com.suixun.lib.httpsqs4j.HttpsqsException;
import com.suixun.service.MessageHistoryService;
import com.suixun.util.Constant;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
/**
 * 
 * <p>Title: SendMessageDeal</p>
 * <p> 功能描述:消息推送调度 </p> 
 * @author	陈显强
 * @date	2017年3月2日下午3:03:20
 * @version 1.0
 */
public class SendMessageDeal extends BaseDeal {
	protected static Logger logger = LoggerFactory.getLogger(SendMessageDeal.class);
	@Resource
	private SendMessageManageDAO sendMessageManageDAO;
	@Resource
	private MessageHistoryService messageHistoryService;
	
	protected static String queueName = "sendmessage";
	
	private final static int COUNT = 900;
	
	private final JPushClient jpushClient = new JPushClient(Constant.JpushConstant.MASTER_SECRET, 
			 Constant.JpushConstant.APP_KEY, null, ClientConfig.getInstance());
	
	private final static ExecutorService executor = Executors.newFixedThreadPool(5);//启用多线程
	
	@Resource
    private HttpsqsClient syssqs;
	
	/**
	 * 扫描消息队列，若有数据，则推送
	 * @throws InterruptedException
	 */
	public void execute() throws InterruptedException {
		if (syssqs != null) {
			try{
				 String result = syssqs.getString(SendMessageDeal.queueName);
				 ObjectMapper mapper = new ObjectMapper();
				 mapper.configure(
                        com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,
                        true);
				 SendMessageInfo sendMessage = mapper.readValue(result, SendMessageInfo.class);
				 List<String> telephones=new LinkedList<>();
				 if (sendMessage.getReceivetype().equals("2") ){
					 String[] telephoneArr = sendMessage.getPeopletels().split("[,，]");
					 for(String telStr : telephoneArr){
						 telephones.add(telStr);
					 }
				 }
				 /*if(sendMessage.getReceivetype() == 1){
					 telephones = sendMessageManageDAO.queryAllParentsTel();
				 }else{
					 String[] telephoneArr = sendMessage.getPeopletels().split("[,，]");
					 for(String telStr : telephoneArr){
						 telephones.add(telStr);
					 }
				 }*/
				 if(sendMessage.getSendtype()==1){
					 /*for (String telephone : telephones) {
						 //将短信内容放到队列里去
						 Map<String,String> arr = new HashMap<>();
						 arr.put("module", "sendMessage");
						 arr.put("title", sendMessage.getTitle());
						 arr.put("telephone", telephone);
						 arr.put("content", sendMessage.getContent());
						 sMSDeal.send(arr);
					 }*/
				 }else{
					 if (sendMessage.getReceivetype().equals("1")) {
						 JiGuangPushAll(sendMessage.getTitle(), 
								 sendMessage.getContent(), true, false, null, jpushClient, "");
						 return;
					 }
					 //极光推送一次不能推送超过1000个用户,大于count个的时候就开始循环
					 List<String> telephoneList =  new ArrayList<>();
					 for (int i = 0 ; i < telephones.size() ; i = i + SendMessageDeal.COUNT) {
						if (i + SendMessageDeal.COUNT >= telephones.size()) {
							telephoneList = telephones.subList(i, telephones.size());
						}else {
							telephoneList = telephones.subList(i, i + SendMessageDeal.COUNT);
						}
						final List<String> telephoneTemps = telephoneList;
						//logger.info("telephone.size = "+telephoneTemps.size()+"----telephoneList:"+JSON.toJSONString(telephoneTemps));
						synchronized (this) {
							Thread.sleep(2000);
							SendMessageDeal.executor.execute(() -> JiGuangPush(telephoneTemps, sendMessage.getTitle(), 
									 sendMessage.getContent(), true, false, null, jpushClient, ""));
						}
					 }
				 }
				 messageHistoryService.addMessage(sendMessage);
			}catch(HttpsqsException e){
			 try {
                 Thread.sleep(1000);
             } catch (InterruptedException e1) {
            	 SendMessageDeal.logger.error(e1.getMessage(), e1);
             }
			}catch (Exception e) {
				SendMessageDeal.logger.error(e.getMessage(), e);
				try {
	                 Thread.sleep(1000);
	             } catch (InterruptedException e1) {
	            	 SendMessageDeal.logger.error(e1.getMessage(), e1);
	             }
            }
		}else {
			SendMessageDeal.logger.error("httpsqsClient is closed");
		}
	}
	
	/*public static void main(String[] args) {
		long start = System.currentTimeMillis();
		SendMessageDeal s = new SendMessageDeal();
		List<String> telephones = new ArrayList<>();
		telephones.add("13320375465");
		telephones.add("13678419967");
		telephones.add("13868113229");
		telephones.add("15123861041");
		telephones.add("15123861043");
		for (int i = 1 ; i < 1000000 ; i ++) {
			telephones.add("1512386104" + i);
		}
		
		List<String> telephoneList =  new ArrayList<>();
		for (int i = 0 ; i < telephones.size() ; i = i + 500) {
			if (i + 500 >= telephones.size()) {
				telephoneList = telephones.subList(i, telephones.size());
			}else {
				telephoneList = telephones.subList(i, i + 500);
			}
			final int j = i;
			final List<String> t = telephoneList;
			//logger.info("i = "+j+"----telephoneList:"+JSON.toJSONString(t));
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					logger.info("i = "+j+"----telephoneList:"+JSON.toJSONString(t));
					
				}
			});
		 }
		System.out.println("执行了"+(System.currentTimeMillis()-start)+"ms");
		//s.test();
	}
	
	public void test() {
		List<String> telephones = new ArrayList<>();
		telephones.add("13320375465");
		telephones.add("13678419967");
		telephones.add("13868113229");
		telephones.add("15123861041");
		
		for (int i = 0 ; i < telephones.size() ; i = i + 500) {
			List<String> telephoneList =  new ArrayList<>();
			if (i+500 >= telephones.size()) {
				telephoneList = telephones.subList(i, telephones.size());
			}else {
				telephoneList = telephones.subList(i, i+500);
			}
		}
		
		
		int count = telephones.size() % 2 == 0 ? telephones.size()/2 : telephones.size()/2+1;
		 for (int i = 0 ; i < count ; i ++) {
			 List<String> telephoneList =  new LinkedList<>();
			 for (int j = i * 2 ; j < (i+1) * 2 ; j ++ ) {
				 if (j < telephones.size()) {
					 telephoneList.add(telephones.get(j));
				 }
			 }
			//调用极光推送
			 JPushClient jpushClient = new JPushClient(Constant.JpushConstant.MASTER_SECRET, 
					 Constant.JpushConstant.APP_KEY, null, ClientConfig.getInstance());
			 JiGuangPush(telephoneList, "暑假来临，随寻推出", 
					 "关注微信号“随寻科技”，回复“投票”，参与此次投票活动，有机会免费获得随寻智能学生证及赠送话费，动动手指，快来参加吧！", true, false, null, jpushClient, "");
		 }
	}*/
}
